<template>
  <el-dialog
    :model-value="modelValue"
    title="版本详情"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div v-loading="loading" class="version-detail">
      <el-descriptions v-if="version" :column="2" border>
        <el-descriptions-item label="版本名称" :span="2">
          {{ version.name }}
        </el-descriptions-item>
        <el-descriptions-item label="版本号">
          {{ version.version_number }}
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <VersionStatusTag :status="castVersionStatus(version.status)" />
        </el-descriptions-item>
        <el-descriptions-item label="所属项目" :span="2">
          {{ version.project_name || '未关联项目' }}
        </el-descriptions-item>
        <el-descriptions-item label="发布类型">
          {{ getReleaseTypeText(version.release_type) }}
        </el-descriptions-item>
        <el-descriptions-item label="部署环境">
          {{ getEnvironmentText(version.environment) }}
        </el-descriptions-item>
        <el-descriptions-item label="计划发布时间">
          {{ formatPlannedDate(version.planned_release_date) || '未设置' }}
        </el-descriptions-item>
        <el-descriptions-item label="实际发布时间">
          {{ version.actual_release_date ? formatDate(version.actual_release_date, 'YYYY-MM-DD HH:mm') : '未发布' }}
        </el-descriptions-item>
        <el-descriptions-item label="计划工时">
          {{ version.planned_work_hours ? `${version.planned_work_hours}h` : '—' }}
        </el-descriptions-item>
        <el-descriptions-item label="创建人">
          {{ version.created_by_name || '—' }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ formatDate(version.created_at, 'YYYY-MM-DD HH:mm') }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间">
          {{ formatDate(version.updated_at, 'YYYY-MM-DD HH:mm') }}
        </el-descriptions-item>
        <el-descriptions-item label="版本描述" :span="2">
          <div class="description-content">
            {{ version.description || '无描述' }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="统计信息" :span="2">
          <div class="stats-info">
            <el-tag type="info" size="small">需求: {{ version.requirement_count || 0 }}</el-tag>
            <el-tag type="primary" size="small">任务: {{ version.task_count || 0 }}</el-tag>
            <el-tag type="warning" size="small">缺陷: {{ version.defect_count || 0 }}</el-tag>
            <el-tag type="success" size="small">发布: {{ version.release_history?.length || 0 }}</el-tag>
          </div>
        </el-descriptions-item>
      </el-descriptions>
      <el-empty v-else description="版本信息加载失败" />
    </div>
    <template #footer>
      <el-button @click="handleClose">关闭</el-button>
      <el-button v-if="canEdit" type="primary" @click="handleEdit">
        编辑
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { versionAPI, type VersionDetailResponse, type VersionStatus, ReleaseType, Environment } from '@/api/version'
import { formatDate } from '@/utils/date'
import VersionStatusTag from './VersionStatusTag.vue'
import { usePermission } from '@/hooks/usePermission'

const props = defineProps<{
  modelValue: boolean
  versionId?: string
}>()

const emit = defineEmits<{
  (event: 'update:modelValue', value: boolean): void
  (event: 'edit', version: VersionDetailResponse): void
}>()

const { hasPermission } = usePermission()

const loading = ref(false)
const version = ref<VersionDetailResponse | null>(null)

const canEdit = computed(() => hasPermission('version:update'))

// 类型转换函数，将字符串状态转换为 VersionStatus 类型
const castVersionStatus = (status?: string | null): VersionStatus => {
  return (status as VersionStatus) || 'planning'
}

watch(
  () => [props.modelValue, props.versionId],
  ([visible, id]) => {
    if (visible && id && typeof id === 'string') {
      loadVersionDetail(id)
    } else {
      version.value = null
    }
  },
  { immediate: true }
)

const loadVersionDetail = async (id: string) => {
  loading.value = true
  try {
    const response = await versionAPI.getVersionById(id)
    if (response.success && response.data) {
      version.value = response.data
    } else {
      ElMessage.error(response.message || '获取版本详情失败')
    }
  } catch (error) {
    console.error('获取版本详情失败:', error)
    ElMessage.error('获取版本详情失败')
  } finally {
    loading.value = false
  }
}

const formatPlannedDate = (date: string | Date | null | undefined): string => {
  if (!date) return ''
  return formatDate(date, 'YYYY-MM-DD HH:mm')
}

const getReleaseTypeText = (type: string | null | undefined): string => {
  if (!type) return '—'
  const map: Record<string, string> = {
    [ReleaseType.MAJOR]: '主版本',
    [ReleaseType.MINOR]: '次版本',
    [ReleaseType.PATCH]: '补丁',
    [ReleaseType.HOTFIX]: '热修复'
  }
  return map[type] || type
}

const getEnvironmentText = (env: string | null | undefined): string => {
  if (!env) return '—'
  const map: Record<string, string> = {
    [Environment.DEVELOPMENT]: '开发环境',
    [Environment.TESTING]: '测试环境',
    [Environment.STAGING]: '预发布环境',
    [Environment.PRODUCTION]: '生产环境'
  }
  return map[env] || env
}

const handleClose = () => {
  emit('update:modelValue', false)
}

const handleEdit = () => {
  if (version.value) {
    emit('edit', version.value)
  }
}
</script>


<style scoped>
.version-detail {
  min-height: 200px;
}

.description-content {
  white-space: pre-wrap;
  word-break: break-word;
  line-height: 1.6;
  color: #606266;
}

.stats-info {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
  color: #606266;
  width: 120px;
}

:deep(.el-descriptions__content) {
  color: #303133;
}
</style>

